//
//  KLMCustomFlowLayout.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/24.
//

import UIKit

class KLMCustomFlowLayout: UICollectionViewFlowLayout {
    
    // MARK: - 可配置参数
    var cellCountPerRow: Int = 2           // 每行/列的 Cell 数量
    var autoCalculateWidth: Bool = true    // 是否自动计算宽度
    var lineSpacing: CGFloat = 16          // 行间距（主轴方向）
    var interitemSpacing: CGFloat = 17     // 列间距（交叉轴方向）
    var sectionTop: CGFloat = 19          // section上下间距
    var sectionLeft: CGFloat = 16         // section左右间距
    var direction: UICollectionView.ScrollDirection = .vertical
    
    // MARK: - 私有属性
    private var contentHeight: CGFloat = 0
    private var contentWidth: CGFloat = 0
    private var cachedAttributes = [UICollectionViewLayoutAttributes]()
    
    
    
    // MARK: - 布局计算
    override func prepare() {
        super.prepare()
        resetLayoutState()
        
        guard let collectionView = collectionView else { return }
        let sectionInset = self.sectionInset
        
        var newSize: CGSize = .zero
        if autoCalculateWidth {
            let totalWidth = collectionView.bounds.width
            let availableWidth = totalWidth - sectionInset.left - sectionInset.right
            let totalInteritemSpacing = CGFloat(cellCountPerRow - 1) * interitemSpacing
            newSize.width = floor((availableWidth - totalInteritemSpacing) / CGFloat(cellCountPerRow))
        } else {
            newSize.width = itemSize.width
        }
        
        
        if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout {
            newSize.height = delegate.collectionView?(collectionView, layout: self, sizeForItemAt: IndexPath(item: 0, section: 0)).height ?? itemSize.height
        }
        
        itemSize = newSize
        
        
//        // 根据滚动方向选择布局逻辑
//        switch scrollDirection {
//        case .vertical:
//            layoutVerticalFlow(collectionView, sectionInset: sectionInset)
//        case .horizontal:
//            layoutHorizontalFlow(collectionView, sectionInset: sectionInset)
//        @unknown default:
//            fatalError("Unsupported scroll direction")
//        }
    }
    
    // 垂直滚动布局
    private func layoutVerticalFlow(_ collectionView: UICollectionView, sectionInset: UIEdgeInsets) {
        let totalWidth = collectionView.bounds.width
        let availableWidth = totalWidth - sectionInset.left - sectionInset.right
        
        // 计算 Cell 宽度（自动计算模式）
        let cellWidth: CGFloat = {
            guard autoCalculateWidth else { return itemSize.width }
            let totalInteritemSpacing = CGFloat(cellCountPerRow - 1) * interitemSpacing
            return floor((availableWidth - totalInteritemSpacing) / CGFloat(cellCountPerRow))
        }()
        
        // 预计算每列的初始 X 坐标
        let xPositions: [CGFloat] = (0..<cellCountPerRow).map { column in
            sectionInset.left + CGFloat(column) * (cellWidth + interitemSpacing)
        }
        
        // 初始化每列的 Y 偏移
        var yOffsets = [CGFloat](repeating: sectionInset.top, count: cellCountPerRow)
        
        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        for item in 0..<numberOfItems {
            let column = item % cellCountPerRow
            let indexPath = IndexPath(item: item, section: 0)
            
            // 动态获取高度（通过代理）
            let cellHeight: CGFloat = {
                if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout {
                    return delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath).height ?? itemSize.height
                }
                return itemSize.height
            }()
            
            // 计算 Frame
            let frame = CGRect(
                x: xPositions[column],       // 使用预计算的固定 X 坐标
                y: yOffsets[column],         // 当前列的 Y 偏移
                width: cellWidth,
                height: cellHeight
            )
            
            print("layoutVerticalFlow frame：", NSCoder.string(for: frame))
            // 缓存布局属性
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            attributes.frame = frame
            cachedAttributes.append(attributes)
            
            // 更新当前列的 Y 偏移（添加行间距）
            yOffsets[column] = frame.maxY + lineSpacing
            
            // 记录最大高度
            contentHeight = max(contentHeight, frame.maxY)
        }
        
        contentWidth = totalWidth
    }
    
    // 水平滚动布局
    private func layoutHorizontalFlow(_ collectionView: UICollectionView, sectionInset: UIEdgeInsets) {
        let totalHeight = collectionView.bounds.height
        let availableHeight = totalHeight - sectionInset.top - sectionInset.bottom
        
        // 计算 Cell 高度
        let cellHeight: CGFloat = {
            guard autoCalculateWidth else { return itemSize.height }
            let totalSpacing = CGFloat(cellCountPerRow - 1) * lineSpacing
            return floor((availableHeight - totalSpacing) / CGFloat(cellCountPerRow))
        }()
        
        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        var xOffsets = [CGFloat](repeating: sectionInset.left, count: cellCountPerRow)
        var yOffsets = [CGFloat](repeating: sectionInset.top, count: cellCountPerRow)
        
        for item in 0..<numberOfItems {
            let row = item % cellCountPerRow
            let indexPath = IndexPath(item: item, section: 0)
            
            // 获取 Cell 宽度（支持代理动态返回）
            let cellWidth: CGFloat = {
                if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout {
                    return delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath).width ?? itemSize.width
                }
                return itemSize.width
            }()
            
            // 计算 Frame
            let frame = CGRect(
                x: xOffsets[row],
                y: yOffsets[row],
                width: cellWidth,
                height: cellHeight
            )
            
            // 缓存布局属性
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            attributes.frame = frame
            cachedAttributes.append(attributes)
            
            // 更新偏移量
            xOffsets[row] = frame.maxX + interitemSpacing
            yOffsets[row] = frame.minY
            contentWidth = max(contentWidth, frame.maxX)
        }
        
        contentHeight = totalHeight
    }
    
    // MARK: - 辅助方法
    private func resetLayoutState() {
        cachedAttributes.removeAll()
        contentHeight = 0
        contentWidth = 0
        
        minimumLineSpacing = lineSpacing
        minimumInteritemSpacing = interitemSpacing
        scrollDirection = direction
        sectionInset = UIEdgeInsets(top: sectionTop, left: sectionLeft, bottom: sectionTop, right: sectionLeft)
    }
    
//    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//        cachedAttributes.filter { $0.frame.intersects(rect) }
//    }
    
//    override var collectionViewContentSize: CGSize {
//        CGSize(width: contentWidth + sectionInset.right, height: contentHeight + sectionInset.bottom)
//    }
    
//    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
//        guard let collectionView = collectionView else { return false }
//        return newBounds.size != collectionView.bounds.size
//    }
}
